package com.ruikong.dazhi.service.impl.baseinfo;

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;
import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.dao.basicinfo.SupplierMapper;
import com.ruikong.dazhi.entity.basicinfo.Shop;
import com.ruikong.dazhi.entity.basicinfo.Supplier;
import com.ruikong.dazhi.model.input.BasePageInput;
import com.ruikong.dazhi.service.basicinfo.ISupplierService;
import com.ruikong.dazhi.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service("SupplierService")
public class SupplierServiceImpl implements ISupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    @Override
    public PageInfo<Supplier> getSupplierListPage(BasePageInput input) {
        PageHelper.startPage(input.getPageNumber(), input.getPageSize());
        List<Supplier> supplierList = this.supplierMapper.getListSearch(input);
        PageInfo<Supplier> pageInfo = new PageInfo<Supplier>(supplierList);

        return pageInfo;
    }

    @Override
    public int addSupplier(Supplier supplier, BaseResult result) {
        Supplier base = supplierMapper.getSupplierByName(supplier.getSupplier_name());
        if (base != null) {
            result.setMsg("已经存在相同供应商名称");
            return 0;
        } else {
            int effect = supplierMapper.insert(supplier);
            if (effect > 0) {
                result.setMsg(ResultApi.addSuccessMsg);
                return effect;
            }
            result.setMsg(ResultApi.addFailMsg);
            return 0;
        }
    }

    @Override
    public int deleteSupplier(Supplier supplier) {
        return this.supplierMapper.deleteById(supplier);
    }

    @Override
    public int updateSupplier(Supplier supplier, BaseResult result) {
        Supplier base = supplierMapper.getSupplierByName(supplier.getSupplier_name());
        if (base != null && !base.getId().equals(supplier.getId())) {
            result.setMsg("请勿修改为相同供应商名称");
            return 0;
        } else {
            int effect = supplierMapper.update(supplier);
            if (effect > 0) {
                result.setMsg(ResultApi.addSuccessMsg);
                return effect;
            }
            result.setMsg(ResultApi.addFailMsg);
            return 0;
        }
    }

    @Override
    public Supplier queryById(int id) {
        return this.supplierMapper.queryById(id);
    }

    @Override
    public List<Supplier> queryAll() {
        return this.supplierMapper.getList();
    }

    @Override
    public BaseResult supplierImport(MultipartFile multipartFile) {
        BaseResult baseResult = new BaseResult();
        //车间集合
        List<Supplier> supplierList = new ArrayList<>();
        try {
            //将multipartFileToFile转化为File
            File file = ExcelUtil.multipartFileToFile(multipartFile);
            InputStream inputStream = new FileInputStream(file);
            String fileName = file.getName();
            String suffix = fileName.split("\\.")[1];
            if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
                baseResult.setMsg("错误！提交文件格式不正确，请上传excel文件");
                baseResult.setCode(ResultApi.failCode);
                return baseResult;
            }
            //xlsx文件使用XSSFWorkbook，否则使用HSSFWorkbook
            Workbook workbook = suffix.equals("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Cell cell = null;
            Row row = null;
            Iterator<Row> iterator = sheet.rowIterator();
            int index = 0;
            while (iterator.hasNext()) {
                row = iterator.next();
                //跳过第一行标题行
                if (0 == index) {
                    index++;
                    continue;
                }
                //供应商
                Supplier supplier = new Supplier();
                //供应商名称
                cell = row.getCell(0);
                String supplier_name;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，供应商名称不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    supplier_name = cell.getStringCellValue().trim();
                    if(supplierMapper.getSupplierByName(supplier_name) != null){
                        baseResult.setMsg(String.format("错误！表格第%s行，供应商名称已存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }else {
                        supplier.setSupplier_name(supplier_name);
                    }

                }
                //联系人
                cell = row.getCell(1);
                String supplier_linkman;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，联系人不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    supplier_linkman = cell.getStringCellValue().trim();
                    supplier.setSupplier_linkman(supplier_linkman);
                }
                //联系电话
                cell = row.getCell(2);
                String supplier_telephone;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，联系电话不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    supplier_telephone = cell.getStringCellValue().trim();
                    supplier.setSupplier_telephone(supplier_telephone);
                }
                //供应商地址
                cell = row.getCell(3);
                String supplier_address;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，供应商地址不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    supplier_address = cell.getStringCellValue().trim();
                    supplier.setSupplier_address(supplier_address);
                }
                //供应商简介
                cell = row.getCell(4);
                String supplier_info;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，供应商简介不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    supplier_info = cell.getStringCellValue().trim();
                    supplier.setSupplier_info(supplier_info);
                }
                supplierList.add(supplier);
                index++;
            }
            baseResult = this.importSave(supplierList);
            file.delete();
        } catch (Exception e) {
            baseResult.setCode(ResultApi.errorCode);
            baseResult.setMsg("供应商导入时出错");
            e.printStackTrace();
        }
        return baseResult;
    }

    //导入信息保存
    public BaseResult importSave(List<Supplier> supplierList) {
        BaseResult baseResult = new BaseResult();
        Shop shop = new Shop();
        try {
            for (int i = 0; i < supplierList.size(); i++) {
                Supplier supplierSave = supplierList.get(i);
                this.supplierMapper.insert(supplierSave);
            }
            baseResult.setMsg("导入成功");
            baseResult.setCode(ResultApi.successCode);
        } catch (Exception e) {
            baseResult.setMsg("导入时出错");
            baseResult.setCode(ResultApi.failCode);
            e.printStackTrace();
        }
        return baseResult;
    }
}
